package cn.icanci.loopstack.bic.sdk.thread;

import cn.icanci.loopstack.bic.sdk.burying.BuryingDTO;
import cn.icanci.loopstack.bic.sdk.properties.BicProperties;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @author icanci
 * @since 1.0 Created in 2023/09/28 14:01
 */
public class TriggerThread {
    private static BicProperties        bicProperties;
    private static BicEscalationService bicEscalationService;

    public static void setBicProperties(BicProperties bicProperties, BicEscalationService bicEscalationService) {
        TriggerThread.bicProperties = bicProperties;
        TriggerThread.bicEscalationService = bicEscalationService;

        start();
    }

    public static void start() {
        // 进行消息通知触达线程
        Thread triggerQueueThread = new Thread(() -> {
            while (true) {
                doTrigger();
            }
        });

        triggerQueueThread.setDaemon(true);
        triggerQueueThread.start();
    }

    private static void doTrigger() {
        try {
            dispatch();
        } catch (Throwable ignored) {
            LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
        } finally {
            parkNanos();
        }
    }

    private static void dispatch() {
        List<BuryingDTO> buryings = BicDataCachePool.take();
        if (!buryings.isEmpty()) {
            bicEscalationService.escalation(buryings);
        }
    }

    private static void parkNanos() {
        try {
            boolean synchronous = bicProperties.isSynchronous();
            if (synchronous) {
                LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
            } else {
                LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(bicProperties.getMaxBatchSubmitTime()));
            }
        } catch (Throwable ignored) {

        }
    }
}
